from django.shortcuts import render
from django.shortcuts import render, HttpResponse, HttpResponsePermanentRedirect, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.db.models import Sum
import time, json, pymysql, collections, os
from app01.models import *
from django.http import JsonResponse
from django import forms
from app01.models import User
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


class UserForm(forms.Form):
    username = forms.CharField()
    headImg = forms.FileField()


class 原型托管UserForm(forms.Form):
    原型 = forms.CharField()
    域名 = forms.CharField()
    备注 = forms.CharField()
    # times = forms.CharField()
    文件 = forms.FileField()


# Create your views here.

cmd1 = '''
cd /dxg/src/dxg-demo-vux &&
git pull &&
cnpm i &&
npm run build &&
rm -rf /dxg/dist/dxg-sdk-h5/* &&
cp -r dist/* /dxg/dist/dxg-sdk-h5/
'''
cmd2 = '''
cd /dxg/src/dxg-demo-vux &&
git pull &&
cnpm i &&
npm run build &&
rm -rf /dxg/dist/dxg-spread-ui/* &&
cp -r dist/* /dxg/dist/dxg-spread-ui/
'''
cmd3 = '''
cd /dxg/src/dxg-spread-admin-ui &&
git pull &&
cnpm i &&
npm run build &&
rm -rf /dxg/dist/dxg-spread-admin-ui/* &&
cp -r dist/* /dxg/dist/dxg-spread-admin-ui/
'''


# cmd1='''hostname'''
def acc_login(request):
    if request.method == "POST":
        print(request.POST)
        user = authenticate(username=request.POST.get("username"), password=request.POST.get("password"))
        if user:
            login(request, user)
            return redirect(request.GET.get('next'))
        else:
            error = "error"
            return render(request, "login.html", {"login_error": error})
    print("用户正在访问登陆页")
    return render(request, "login.html")


@login_required
def acc_logout(requrst):
    logout(requrst)
    return redirect("/")


@login_required
def index(request):
    if request.method == "POST":

        uf = 原型托管UserForm(request.POST, request.FILES)
        if uf.is_valid():
            # 获取表单信息
            print(uf.cleaned_data)
            原型 = uf.cleaned_data['原型']
            域名 = uf.cleaned_data['域名']
            备注 = uf.cleaned_data['备注']
            文件 = uf.cleaned_data['文件']
            目录 = str(文件).replace('.zip', '')
            目录 = 目录.replace('.tar.gz', '')
            域名 = os.path.join(域名, 目录)
            # print(headImg)
            原型托管.objects.filter(原型=原型).delete()
            # 写入数据库
            user = 原型托管()
            user.原型 = 原型
            user.域名 = 域名
            user.备注 = 备注
            user.times = time.strftime('%Y-%m-%d %H:%M')
            user.headImg = 文件
            user.save()
            cmd_path = 文件解压路径.objects.all().order_by('-id')[0:1]
            for item in cmd_path:
                os.system("rm -rf {}".format(os.path.join(item.路径, 目录)))
                os.system("cd upload/ && {} {} -d {} && rm -rf {}".format(item.解压命令, 文件, item.路径, 文件))
                # print(文件)
                # print(item.路径,item.解压命令)

            # return render(request, 'success.html', )
    else:
        uf = 原型托管UserForm()

    if request.is_ajax():
        if request.method == "GET":
            # print(request.GET)
            # 删除功能代码
            if request.GET['delete'] == 'ok':
                # print(request.GET['序号'])
                dele = 原型托管(id=request.GET['序号'])
                dele.delete()

    data1 = 原型托管.objects.all()
    paginator = Paginator(data1, 5)  # 每页显示5个
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # 如果页面不是整数，请提供第一页。
        contacts = paginator.page(1)
    except EmptyPage:
        # 如果页面超出范围（例如9999），则提供最后一页的结果。
        contacts = paginator.page(paginator.num_pages)
    data1 = contacts

    data2 = []
    for i in data1:
        # print(i)
        data2.append({"序号": i.id,
                      "原型": i.原型,
                      "域名": i.域名,
                      "备注": i.备注,
                      "时间": str(i.times)[:19]})
    print("用户正在访问主页")
    return render(request, 'index.html', {"data1": data1, "uf": uf, "data2": json.dumps(data2), "contacts": contacts,
                                          "页的序号": range(1, contacts.paginator.num_pages + 1)})


def getdata(request):
    data1 = 原型托管.objects.all()
    paginator = Paginator(data1, 5)  # 每页显示5个
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # 如果页面不是整数，请提供第一页。
        contacts = paginator.page(1)
    except EmptyPage:
        # 如果页面超出范围（例如9999），则提供最后一页的结果。
        contacts = paginator.page(paginator.num_pages)
    data1 = contacts
    data2 = []
    for i in data1:
        # print(i)
        data2.append({"序号": i.id,
                      "原型": i.原型,
                      "域名": i.域名,
                      "备注": i.备注,
                      "时间": str(i.times)[:19]})
    return JsonResponse(data2, safe=False)


def getdomain(request):
    dom = 域名配置.objects.all()[0:1]
    for i in dom:
        域名 = {"域名": i.domain}
        return JsonResponse(域名, safe=False)


@login_required
def register(request):
    data = User.objects.all()
    if request.method == "POST":
        uf = UserForm(request.POST, request.FILES)
        if uf.is_valid():
            # 获取表单信息
            username = uf.cleaned_data['username']
            headImg = uf.cleaned_data['headImg']
            # print(headImg)
            # 写入数据库
            user = User()
            user.username = username
            user.headImg = headImg
            user.save()

            return render(request, "register.html", {'uf': uf, "put": "上传成功", "data": data})


    else:
        uf = UserForm()
    # return render_to_response('register.html', {'uf': uf},)
    return render(request, "register.html", {'uf': uf, "data": data})
